package com.cheetah.start.common.listener;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 在线管理
 *
 * @author Feel
 * @date 2021/08/10
 */
@Data
@Slf4j
public class OnLineManager {
    private static OnLineManager om;
    private Map<String, HttpSession> sessions;

    private OnLineManager() {
        sessions = new HashMap<String, HttpSession>();
    }

    public static OnLineManager getInstance() {
        if (om == null) {
            om = new OnLineManager();
        }
        return om;
    }

    /**
     * 添加会话
     *
     * @param se se
     */
    public void addSession(HttpSession se) {
        String id = se.getId();
        sessions.put(id, se);
        log.info("add :[{}] : ", sessions.size());

    }

    /**
     * 删除会话
     *
     * @param se se
     */
    public void removeSession(HttpSession se) {
        String id = se.getId();
        sessions.remove(id);
        log.info("remove 1 : " + "key:" + id + sessions.size());
        log.info("sessions:[{}]", sessions);
    }

    /**
     * 获得会话
     *
     * @param sessionId 会话 id
     * @return {@link HttpSession}
     */
    public HttpSession getSession(String sessionId) {
        return sessions.get(sessionId);
    }
}
